package com.bw.common.base

import android.util.Log
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.common.entity.Res
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.onStart

import kotlinx.coroutines.launch


abstract class BaseViewModel : ViewModel() {

// 通用Flow请求封装（处理Res包装）
    protected fun <T> launchFlow(
    flow: Flow<Res<T>>,
    onStart: () -> Unit = {},
    onSuccess: (T) -> Unit,
    onError: (String) -> Unit = { _ -> }
    ) {
        viewModelScope.launch {
            flow
                .onStart { onStart() }
                .catch { e -> onError(e.message ?: "Flow error") }
                .collect { res ->
                    Log.d("TAG", "launchFlow: woshse")
                    when (res.code) {
                        200 -> res.data?.let { onSuccess(it) }
                        else -> onError(res.message ?: "Request failed")
                    }
                }
        }
    }
}
